#include "http.h"

void handleStaticFile(const char *filePath, const HTTPRequest *request, HTTPResponse *response) {
    HTTPHeader header;
    // 文件不存在
    if (!isFile(filePath)) goto notFound;
    // 设置缓存策略
    header.key = "Cache-Control";
    header.value = "no-cache";
    setHeader(&response->headers, header);
    // 计算lastModify并设置头部
    char lastModify[32];
    if (!lastModifyOfFile(filePath, lastModify, 32)) goto onError;
    header.key = "Last-Modified";
    header.value = lastModify;
    setHeader(&response->headers, header);
    // 获取If-Modified-Since并计算是否文件已更新
    const char *modifySince = getHeaderValueByKey(&request->headers, "If-Modified-Since");
    if (modifySince == NULL) goto sendFullFile;
    if (strcmp(modifySince, lastModify) == 0) goto notModified;
    return;

sendFullFile:
    response->code = HTTP_OK;
    makeFilePathResponse(response, filePath);
    return;
notModified:
    response->code = HTTP_NOT_MODIFIED;
    return;
notFound:
    response->code = HTTP_NOT_FOUND;
    return;
onError:
    response->code = HTTP_INTERNAL_SERVER_ERROR;
    return;
}


void handleStaticResourceDir(const char *resDir, const HTTPRequest *request, HTTPResponse *response) {
    // 计算文件路径
    char filePath[strlen(request->path) + strlen(resDir) + 1];
    strcpy(filePath, resDir);
    strcat(filePath, request->path);
    handleStaticFile(filePath, request, response);
}
